<?php

namespace App\Api\V1\Controllers;

use App\Models\Behavior;
use App\Models\Behavior\Cat;
use App\Models\Family;
use App\Models\Points;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Exceptions\JWTException;

class UserController extends Controller
{
    protected $guard = 'api';

    /**
     * 根据用户id获取用户信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserById(Request $request)
    {
        $this->validate($request, [
            'user_id' => 'required',
        ]);

        $user_id = $request->user_id;

        if (!$user_id)
            return response()->json([
                'status_code' => 0,
                'message'     => '用户不存在'
            ]);

        $data = User::where('user_id', $user_id)
            ->leftJoin('love_points as b', 'b.user_id', 'love_users.id')
            ->selectRaw('love_users.id,love_users.username,love_users.avatar,love_users.mobile,love_users.gender,
                b.points,b.positive_points,b.negative_points')
            ->first();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 根据二维码获取用户信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserByQrCode(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
        ]);

        $qrcode    = $request->code;
        //$user_id = base64_decode($code);

        if (!$qrcode)
            return response()->json([
                'status_code' => 0,
                'message'     => '用户不存在'
            ]);

        $data = User::where('qrcode', $qrcode)
            ->leftJoin('love_points as b', 'b.user_id', 'love_users.id')
            ->selectRaw('love_users.id,love_users.username,love_users.avatar,love_users.mobile,love_users.gender,
            b.points,b.positive_points,b.negative_points')
            ->first();

        if ($data) {
            return response()->json([
                'status_code' => 1,
                'message'     => 'success',
                'data'        => $data
            ]);
        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '查无此人',
            ]);
        }


    }

    public function bindUserQrCode(Request $request)
    {
        $this->validate($request, [
            'user_id' => 'required',
            'qrcode' => 'required',
        ]);

        $user = User::find($request->user_id);
        if ($user) {
            $user->qrcode = $request->qrcode;
            $flag = $user->update();
            if ($flag) {
                $status_code = 1;
                $message = '绑定成功';
            } else {
                $status_code = 0;
                $message = '绑定失败';
            }
        } else {
            $status_code = 0;
            $message = '绑定失败';
        }

        return response()->json([
            'status_code' => $status_code,
            'message'     => $message,
        ]);

    }

    /**
     * 获取用户列表
     */
    public function getUsers(Request $request)
    {
        $keywords = $request->key;

        $row = User::when($keywords, function ($query) use ($keywords){
                return $query->where('username','like','%'.$keywords.'%');
            })
            ->leftJoin('love_points as b', 'b.user_id', 'love_users.id')
            ->leftJoin('love_family_users as c', 'c.user_id', 'love_users.id')
            ->selectRaw('love_users.id,love_users.username,love_users.avatar,love_users.mobile,
                love_users.gender,b.points,b.positive_points,b.negative_points,
                (case when c.is_householder = 1 then 1 else 0 end) is_householder
            ')
            ->paginate(10)->toArray();

        $data = [];
        if ($row) {
            $data['current_page'] = $row['current_page'];
            $data['total_page'] = $row['last_page'];
            $data['data'] = $row['data'];
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 添加户主
     *
     * @param Request $request
     */
    public function addUser(Request $request)
    {
        $this->validate($request, [
            'mobile'         => 'required',
            'username'       => 'required',
            'family_number'  => 'required',
            'family_address' => 'required',
        ]);

        $user = User::where('mobile', $request->mobile)->count();
        if ($user)
            return response()->json([
                'status_code' => 0,
                'message'     => '手机号已存在',
            ]);

        $family = Family::where('number', $request->family_number)->count();
        if ($family)
            return response()->json([
                'status_code' => 0,
                'message'     => '户号已存在',
            ]);


        DB::beginTransaction();
        try {

            $user = new User();
            $user->username = $request->username;
            $user->mobile = $request->mobile;
            $user->avatar = 'images/user.jpg';

            $flag1 = $user->save();

            if ($flag1) {
                $user_id = $user->id;

                $family = new Family();
                $family->number = $request->family_number;
                $family->address = $request->family_address;
                $family->householder_id = $user_id;

                $flag2 = $family->save();

                if ($flag2) {
                    $family_id = $family->id;

                    $family_user = new Family\User();
                    $family_user->family_id = $family_id;
                    $family_user->user_id = $user_id;
                    $family_user->is_householder = 1;

                    $flag3 = $family_user->save();

                    if ($flag3) {
                        $points = Points::where('user_id', $user_id)->count();

                        if (!$points){
                            $points_initial = 0;

                            $setting = Points\Setting::first();
                            if ($setting){
                                $points_initial = $setting['points_initial'];
                            }
                            $points = new Points;
                            $points->user_id = $user_id;
                            $points->points = $points_initial;
                            $flag4 = $points->save();
                        }
                    }
                }
            }


            if($flag1 && $flag2 && $flag3 && $flag4){
                DB::commit();
                $status = 1;
                $message = '添加成功';
            } else {

                DB::rollBack();
                $status = 0;
                $message = '添加失败';
            }
        } catch (\Exception $e) {
            DB::rollBack();
            $status = 0;
            $message = '添加失败';
        }


        return response()->json([
            'status_code' => $status,
            'message'     => $message,
        ]);

    }

    /**
     * 删除用户
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeUser(Request $request)
    {
        $this->validate($request, [
            'user_id'         => 'required',
        ]);

        DB::beginTransaction();

        try {
            $flag1 = User::where('id', $request->user_id)->delete();
            $flag2 = Points::where('user_id', $request->user_id)->delete();

            if ($flag1 && $flag2) {
                DB::commit();
                $status = 1;
                $message = '删除成功';
            } else {
                DB::rollBack();
                $status = 0;
                $message = '删除失败';
            }
        } catch (\Exception $e) {
            DB::rollBack();
            $status = 0;
            $message = '删除失败';
        }

        return response()->json([
            'status_code' => $status,
            'message'     => $message,
        ]);

    }

    /**
     * 修改用户信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUser(Request $request)
    {
        $avatar = $request->avatar;
        $username = $request->username;
        $birthday = $request->birthday;
        $gender = $request->gender;

        if ($avatar || $username || $birthday || $gender) {

            $user = $user = Auth::guard($this->guard)->user();

            $u = User::find($user['id']);
            if (!$u)
                return response()->json([
                    'status_code' => 0,
                    'message'     => '用户不存在',
                ]);

            if ($avatar)
                $u->avatar = $avatar;
            if ($username)
                $u->username = $username;
            if ($birthday)
                $u->birthday = $birthday;
            if ($gender) {
                if (in_array($gender, [0,1,2]))
                    $u->gender = $gender;
                else
                    return response()->json([
                        'status_code' => 0,
                        'message'     => '修改失败',
                    ]);
            }

            $flag = $u->save();

            if ($flag)
                return response()->json([
                    'status_code' => 1,
                    'message'     => '修改成功',
                ]);
            else
                return response()->json([
                    'status_code' => 0,
                    'message'     => '修改失败',
                ]);

        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '参数错误',
            ]);
        }
    }

    /**
     * 修改手机号--验证手机号/发送验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendCode(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'step'   => 'required',
        ]);

        $mobile = $request->mobile;
        $step   = $request->step;

        $user = $user = Auth::guard($this->guard)->user();

        if ($step == 1) {
            if ($mobile != $user['mobile'])
                return response()->json([
                    'status_code' => 0,
                    'message'     => '手机号不正确',
                ]);
        } else if ($step == 2) {
            $redis_key = 'user:modify:validate:' . $user['mobile'];
            if (!Redis::GET($redis_key)) {
                return response()->json([
                    'status_code' => 0,
                    'message'     => '禁止访问',
                ]);
            }

            $user_count = User::where('mobile', $mobile)->count();
            if ($user_count)
                return response()->json([
                    'status_code' => 0,
                    'message'     => '手机号已被使用',
                ]);
        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '参数错误',
            ]);
        }

        $code = mt_rand(100000,999999);

        $content = "您的验证码是：{$code}，如非本人操作请忽视。";

        $result = sms($mobile, $content);

        if ($result) {
            $redis_key = "user:modify:$step:" . $mobile;
            $flag      = Redis::SET($redis_key, $code);

            if ($flag) {
                Redis::EXPIRE($redis_key, 300);
                $status_code = 1;
                $message     = '发送成功';
            } else {
                $status_code = 0;
                $message     = '发送失败';
            }


        } else {
            $status_code = 0;
            $message     = '发送失败';
        }

        return response()->json([
            'status_code' => $status_code,
            'message'     => $message,
            'code'        => $code
        ]);
    }

    /**
     * 修改手机号--验证验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function validateCode(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'code'   => 'required',
            'step'   => 'required',
        ]);

        $mobile = $request->mobile;
        $code = $request->code;
        $step = $request->step;

        $user = $user = Auth::guard($this->guard)->user();

        if ($step == 1) {

            if ($mobile != $user['mobile'])
                return response()->json([
                    'status_code' => 0,
                    'message'     => '手机号不正确',
                ]);

            $redis_key = "user:modify:$step:" . $mobile;
            if ($code != Redis::GET($redis_key))
                return response()->json([
                    'status_code' => 0,
                    'message'     => '验证码不正确',
                ]);

            Redis::DEL($redis_key);

            $redis_key = 'user:modify:validate:' . $mobile;
            Redis::SET($redis_key, 1);
            Redis::EXPIRE($redis_key, 300);

            return response()->json([
                'status_code' => 1,
                'message'     => '验证成功',
            ]);

        } else if ($step == 2) {

            $user_count = User::where('mobile', $mobile)->count();
            if ($user_count)
                return response()->json([
                    'status_code' => 0,
                    'message'     => '手机号已被使用',
                ]);

            $redis_key = "user:modify:$step:" . $mobile;
            if ($code != Redis::GET($redis_key))
                return response()->json([
                    'status_code' => 0,
                    'message'     => '验证码不正确',
                ]);


            $u = User::find($user['id']);

            if (!$u)
                return response()->json([
                    'status_code' => 0,
                    'message'     => '用户不存在',
                ]);

            $u->mobile = $mobile;

            $flag = $u->update();


            if ($flag) {
                Redis::DEL($redis_key);

                $redis_key = 'user:modify:validate:' . $mobile;
                Redis::DEL($redis_key);

                return response()->json([
                    'status_code' => 1,
                    'message'     => '修改成功',
                ]);

            } else {
                return response()->json([
                    'status_code' => 0,
                    'message'     => '修改失败',
                ]);
            }

        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '参数错误',
            ]);
        }

    }





}
